package com.laosg.framework.fhir.springboot.util;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.Map;

public class JacksonUtil {

    private static final Logger logger = LoggerFactory.getLogger(JacksonUtil.class);

    private static final JacksonUtil nonEmptyJacksonMapper;

    static {
        nonEmptyJacksonMapper = new JacksonUtil(Include.NON_EMPTY);
    }

    private ObjectMapper mapper;

    public JacksonUtil() {
        this(null);
    }

    public JacksonUtil(Include include) {
        mapper = new ObjectMapper();
        // 设置输出时包含属性的风格
        if (include != null) {
            mapper.setSerializationInclusion(include);
        }
        // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    /**
     * 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用.
     */
    public static JacksonUtil nonEmptyMapper() {
        return nonEmptyJacksonMapper;
    }

    /**
     * Object可以是POJO，也可以是Collection或数组。 如果对象为Null, 返回"null". 如果集合为空集合, 返回"[]".
     */
    public String toJson(Object object) {

        try {
            return mapper.writeValueAsString(object);
        } catch (Exception e) {
            logger.warn("write to json string error:" + object, e);
            return null;
        }
    }

    private static final String PARSE_ERROR = "parse json string error:";


    /**
     * 反序列化POJO或简单Collection如List<String>.
     *
     * 如果JSON字符串为Null或"null"字符串, 返回Null. 如果JSON字符串为"[]", 返回空集合.
     *
     * 如需反序列化复杂Collection如List<MyBean>, 请使用fromJson(String, JavaType)
     *
     * @see #fromJson(String, JavaType)
     */
    public <T> T fromJson(String jsonString, Class<T> clazz) {
        if (jsonString == null || "".equals(jsonString)) {
            return null;
        }

        try {
            return mapper.readValue(jsonString, clazz);
        } catch (Exception e) {
            logger.warn(PARSE_ERROR + jsonString, e);
            return null;
        }
    }

    /**
     * 反序列化复杂Collection如List<Bean>,
     * 先使用createCollectionType()或contructMapType()构造类型, 然后调用本函数.
     *
     */
    public <T> T fromJson(String jsonString, JavaType javaType) {
        if (jsonString == null || "".equals(jsonString)) {
            return null;
        }

        try {
            return mapper.readValue(jsonString, javaType);
        } catch (Exception e) {
            logger.warn(PARSE_ERROR + jsonString, e);
            return null;
        }
    }

    /**
     * 如存在多重泛型，如TypeReference<ResponseData<List<User>>>
     */
    public <T> T fromJson(String jsonString, TypeReference<T> reference) {
        if (jsonString == null || "".equals(jsonString)) {
            return null;
        }

        try {
            return mapper.readValue(jsonString, reference);
        } catch (Exception e) {
            logger.warn(PARSE_ERROR + jsonString, e);
            return null;
        }
    }

    /**
     * 构造Collection类型.
     */
    @SuppressWarnings("rawtypes")
    public JavaType contructCollectionType(Class<? extends Collection> collectionClass, Class<?> elementClass) {
        return mapper.getTypeFactory().constructCollectionType(collectionClass, elementClass);
    }

    /**
     * 构造Map类型.
     */
    @SuppressWarnings("rawtypes")
    public JavaType contructMapType(Class<? extends Map> mapClass, Class<?> keyClass, Class<?> valueClass) {
        return mapper.getTypeFactory().constructMapType(mapClass, keyClass, valueClass);
    }

    /**
     * 当JSON里只含有Bean的部分屬性時，更新一個已存在Bean，只覆蓋該部分的屬性.
     */
    public void update(String jsonString, Object object) {
        try {
            mapper.readerForUpdating(object).readValue(jsonString);
        } catch (JsonProcessingException e) {
            logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
        } catch (Exception e) {
            logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
        }
    }

    /**
     * 輸出JSONP格式數據.
     */
    public String toJsonP(String functionName, Object object) {
        return toJson(new JSONPObject(functionName, object));
    }

    /**
     * 取出Mapper做进一步的设置或使用其他序列化API.
     */
    public ObjectMapper getMapper() {
        return mapper;
    }

    public static void main(String[] args) {

        System.out.println("----------------");


        String xx="{\"applyId\":\"0\",\"id\":\"50\",\"type\":\"deal_receipt\"}";


//        Map<String,String> map = JSON.parseObject(xx, Map.class);
        ObjectMapper mapper=new ObjectMapper();
        try {
            /*Map<String,String> map = (Map) JSONObject.parse(xx);
            for (Map.Entry<String, String> entry : map.entrySet()) {
                System.out.println(entry.getKey()+" "+entry.getValue());
            }*/
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
